package com.flame.workflow.ru.engine.handler;

import com.flame.workflow.constants.RuntimeConstants;
import com.flame.workflow.constants.TaskConstants;
import com.flame.workflow.constants.UserTaskConstants;
import com.flame.workflow.ru.engine.context.RuntimeContext;
import com.flame.workflow.ru.entity.Task;
import com.flame.workflow.ru.trigger.TriggerTask;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @author wuxintong😺😺😺
 * @since 2023/6/6
 */
@Service("workflow-trigger-task-handler")
public class TriggerTaskHandler extends AbstractTaskHandler implements ApplicationContextAware {

    private Map<String, TriggerTask> triggerTaskMap;

    @Override
    public String runTask(RuntimeContext runtimeContext) {
        Task task = runtimeContext.getTask();
        userTaskService.addUserTask(task.getInstanceId(), task.getTaskId(), TriggerTask.USER_ID);

        TriggerTask triggerTask = triggerTaskMap.get(TriggerTask.DEFAULT_TRIGGER_TASK);
        String triggerTargetName = task.getTaskProperties().get("triggerTarget");
        if (StringUtils.hasText(triggerTargetName) && triggerTaskMap.containsKey(triggerTargetName)) {
            triggerTask = triggerTaskMap.get(triggerTargetName);
        }

        boolean success = triggerTask.invoke(runtimeContext);

        if (success) {
            userTaskService.completeByTaskIdAndUserId(task.getTaskId(), TriggerTask.USER_ID, UserTaskConstants.USER_TASK_STATUS_COMPLETE_SUCCESS, false);
            return RuntimeConstants.RUNTIME_STATUS_COMPLETE;
        }
        userTaskService.completeByTaskIdAndUserId(task.getTaskId(), "system", UserTaskConstants.USER_TASK_STATUS_COMPLETE_ERROR, false);
        return RuntimeConstants.RUNTIME_STATUS_ERROR;
    }

    @Override
    public String taskType() {
        return TaskConstants.TASK_TYPE_TRIGGER;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.triggerTaskMap = applicationContext.getBeansOfType(TriggerTask.class);
    }
}
